package cn.com.edaily;

import cn.com.edaily.auth.utils.UuidUtil;
import cn.com.edaily.cmp.User;
import cn.com.edaily.cmp.UserKey;
import cn.com.edaily.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/spring/test-context.xml"})
public class Main {

	@Autowired
	private UserMapper userMapper;

	@Test
	public void test1() throws IOException {
		// 指定全局配置文件
		String resource = "mybatis-config.xml";
		// 读取配置文件
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 构建sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// 获取sqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			// 操作CRUD，第一个参数：指定statement，规则：命名空间+“.”+statementId
			// 第二个参数：指定传入sql的参数：这里是用户id
			UserKey userKey = new UserKey(1, "111");
			User user = sqlSession.selectOne("cn.com.edaily.dao.UserMapper.selectByPrimaryKey", userKey);
			System.out.println(user);
		} finally {
			sqlSession.close();
		}
	}

	@Test
	public void test2() throws IOException, XMLParserException, InvalidConfigurationException, SQLException,
			InterruptedException {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		File configFile = new File("D:\\version\\mayun\\edaily-core\\edaily\\mbg.xml");
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
		System.out.println("success");
	}

	@Test
	public void test3() {
		System.out.println(UuidUtil.generateUuid());
	}

	@Test
	public void getUser() {
		System.out.println(userMapper.selectByUserName("web_chen@163.com").size());
		System.out.println(userMapper.selectByUserName("web_chen@163.com").get(0).getUsername());
	}
}
